<?php

function add_item($key,$quantity)
{
    global $products;
    if($quantity<1) return;
    if(isset($_SESSION['cart1'][$key]))
    {
        $quantity+=$_SESSION['cart1'][$key]['qty'];
        update_item($key,$quantity);
        return;
    }
    $cost=$products[$key]['cost'];
    $total=$cost* $quantity;
    $item=array(
      'name'=>$products[$key]['name'],
        'cost'=>$cost,
        'qty'=>$quantity,
        'total'=>$total
    );
    
    $_SESSION['cart1'][$key]=$item;
}

function update_item($key,$quantity)
{
    global $products;
    $quantity=(int)$quantity;
    if(isset($_SESSION['cart1'][$key]))
    {
        if($quantity<0)
        {
            unset($_SESSION['cart1'][$key]);
            
        }
        else
        {
            $_SESSION['cart1'][$key]['qty']=$quantity;
            $total=$_SESSION['cart1'][$key]['qty'] * $_SESSION['cart1'][$key]['cost'];
            $_SESSION['cart1'][$key]['total']=$total;
        }
    }
    
   function get_subtotal()
   {
       $subtotal=0;
       foreach($_SESSION['cart1'] as $item)
       {
           $subtotal+=$item['total'];
       }
       $subtotal=  number_format($subtotal,2);
       return $subtotal;
   }
}
?>
